import {Component, OnInit} from '@angular/core';
import {CommonService} from "../../service/base/common.service";
import {UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {LoginHttpService} from "../../service/http/login.http.service";
import {HttpCustomConfig} from "../../service/base/base.http.service";
import {SpUtil} from "../../util/SpUtil";

@Component({
  selector: 'app-welcome',
  templateUrl: './welcome.component.html',
  styleUrls: ['./welcome.component.less']
})
export class WelcomeComponent implements OnInit, HttpCustomConfig {

  validateForm!: UntypedFormGroup;

  constructor(private commonService: CommonService, private fb: UntypedFormBuilder, private loginHttpService: LoginHttpService) {
  }

  showLoading: boolean = false;

  ngOnInit() {
    this.validateForm = this.fb.group({
      mobile: [SpUtil.get('account'), [Validators.required]],
      pwd: [null, [Validators.required]],
      rem: [true]
    });
  }

  submitForm(): void {
    if (this.validateForm.valid) {
      this.login();
    } else {
      Object.values(this.validateForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  login(): void {

    console.log(this.validateForm.value);
    this.loginHttpService.post({account: this.validateForm.value.mobile, pwd: this.validateForm.value.pwd}, this)
      .subscribe((resJson: any): void => {
        console.log(resJson.data.token);
        SpUtil.setAdminInfo(resJson.data);
        if (this.validateForm.value.rem) {
          SpUtil.set('account', this.validateForm.value.mobile);
        }
        this.commonService.intent('/home');
      })
  }

  forgetPwd(): void {
    this.commonService.toast('请联系管理员重置密码');
  }

}
